/***
 *
 * @props
 * title 模块名
 * helpPath  帮助文档地址
 * logoutPath 退出登录接口地址
 *
 * @sessionStroage
 * token 
 * token 基础平台地址
 * officeUrl 办公平台地址 264
 * noticeUrl 消息中心地址 211
 * identityCode 身份码
 * userInfo 用户信息
 * sysInfo 系统信息
 * 
 */

import React, { Component } from "react";
import fetch from "../../../util/fetch";
import md5 from "md5";
import "./index.scss";
import { lgAlert, LgTopBarContainer } from "lancoo-web-ui";
import { loadScriptOrCss, removeToken } from "./public";
import IdentityIcon from "./identityIcon"
class App extends Component {
	constructor(props) {
		super(props);
	}
	state = {
		token: sessionStorage.getItem("token"),
		baseUrl: sessionStorage.getItem("baseUrl"),
    officeUrl: sessionStorage.getItem("officeUrl"),
		noticeUrl: sessionStorage.getItem("noticeUrl"),
    identityCode: sessionStorage.getItem("identityCode"),
		userInfo: JSON.parse(sessionStorage.getItem("userInfo") || "{}"),
		sysInfo: JSON.parse(sessionStorage.getItem("sysInfo") || "{}"),

    identityInfo: {},
	};
  componentDidMount(){
    this.handleUserIc()
    this.noticeInit()
  }
  // 处理用户当前身份
  handleUserIc = () => {
    let { userInfo, identityCode } = this.state
    let infos = userInfo.identityInfos || []
    let identityInfo = infos[0]
    infos.forEach(item => {
      if(item.identityCode === identityCode){
        identityInfo = item
      }
    })
    this.setState({ identityInfo })
  }
	// 小铃铛
	noticeInit = () => {
		let { token, baseUrl, noticeUrl } = this.state;
		if (!noticeUrl) {
      let noticeSysId = "211"
      let mdToken210 = md5(noticeSysId).split('').reverse().join('')
      fetch.get({
        url: baseUrl + '/BaseApi/Global/GetSubSystemsMainServerBySubjectID',
        params: {
          appid: noticeSysId,
          access_token: mdToken210,
          sysIDs: noticeSysId
        }
      }).then(res => res.json()).then(res => {
        if(res.StatusCode == 200 && res.Data){
          noticeUrl = res.Data[0].WebSvrAddr
          _setMustInfo()

          this.setState({ noticeUrl })
        }else{
          console.log("获取消息中心地址失败...");
        }
      })
      return
		}
    _setMustInfo()

    function _setMustInfo(){
      sessionStorage.setItem("PsnMgrToken", token); //用户Token
      sessionStorage.setItem("PsnMgrMainServerAddr", baseUrl); //基础平台IP地址和端口号 形如：http://192.168.129.1:30103/
      sessionStorage.setItem("PsnMgrLgAssistantAddr", noticeUrl); //个人信息管理系统Web站点IP地址和端口号 形如：http://192.168.129.1:10103/
      let arr = [
        noticeUrl + "/PsnMgr/LgAssistant/js/jquery-1.7.2.min.js",
        noticeUrl + "/PsnMgr/LgAssistant/assets/jquery.pagination.js",
        noticeUrl +
          "/PsnMgr/LgAssistant/js/lancoo.cp.assistantInfoCenter.js",
        noticeUrl +
          "/PsnMgr/LgAssistant/css/lancoo.cp.assistantInfoCenter.css",
      ].reverse();
      loadScriptOrCss(arr);
    }
	};
	// 跳转办公平台
	toPlatFrom = () => {
    let { token, officeUrl } = this.state
		window.open(officeUrl + "homepage/web/index.html?lg_tk=" + token, "_blank");
	};
	// 跳转帮助文档
	toHelp = () => {
    let { token, sysInfo } = this.state
		let helpPath = this.props.helpPath;
		window.open(sysInfo.itemUrl + helpPath + "?lg_tk=" + token, "_blank");
	};
	// 跳转个人中心
	toPerson = () => {
    let { token, baseUrl, sysInfo } = this.state
		let url = "/UserMgr/PersonalMgr/Default.aspx";
		if (sysInfo.iscVersion >= 4) {
			url = "html/personalMgr";
		}
		window.open(baseUrl + url + "?lg_tk=" + token, "_blank");
	};
	// 退出登录
	logout = () => {
		let alert = lgAlert.show({
			duration: 0,
			content: "是否退出登录？",
			tipType: "question",
			description: " ",
			tipSize: "big",
			tipMouldType: "A",
			showCover: true,
			coverZIndex: 1200,
			position: {
				xAxis: "center",
				yAxis: "center",
			},
			confirmText: "确定",
			closeText: "取消",
			onConfirm: () => {
        let { token, baseUrl, userInfo, sysInfo } = this.state
				let { logoutPath } = this.props;
        let sysId = sysInfo.sysId || sessionStorage.getItem("sysId") || ""
				let url = sysInfo.itemUrl + logoutPath;
				let method = "get";
				let obj = {
					token: token,
					sysId: sysId,
					appid: sysId,
					UserID: userInfo.userId,
					DeviceType: 2,
				};
				if (sysInfo.iscVersion >= 4) {
					url = baseUrl + "/BaseApi/Login/Logout";
					method = "post";
				}
				fetch[method]({
					url,
					params: obj,
					body: obj,
				})
					.then((res) => res.json())
					.then((result) => {
						if (result.code == 200 || result.StatusCode == 200) {
							let str = removeToken(window.location.href);
							window.location =
								baseUrl +
								"login.html?lg_sysid=" + 
                sysId +
                "&lg_preurl=" +
								encodeURIComponent(str);
							sessionStorage.removeItem("token");
						}
					});
				lgAlert.close(alert.index);
			},
		});
	};
	render() {
		let { title = "title", helpPath } = this.props;
		let {
      userInfo,
      identityInfo,
    } = this.state;
		return (
      <LgTopBarContainer className="app_header">
				<div className="header_container">
					<div className="app_logo"></div>
					<div className="app_name">{title}</div>
					<div className="header_btn">
						<span className="btn_work" onClick={this.toPlatFrom}>
							返回办公平台
						</span>
						<span className="slice_line"></span>
						<span className="btn_message">
							<i id="Assistant_infoCenter"></i>
							<span
								onClick={() => {
									document.querySelector("#Assistant_infoCenter").click();
								}}
							>
								消息
							</span>
						</span>
            {
              helpPath?
              <span className="btn_help" onClick={this.toHelp}>
                帮助
              </span>:
              ""
            }
            <span className="slice_line"></span>
						<div className="user_info" onClick={this.toPerson}>
							<i
								className="user_avatar"
								style={{
									backgroundImage: `url('${userInfo.photoPath}')`,
								}}
							></i>
							<span className="user_name">{userInfo.userName}</span>
              <IdentityIcon userType={userInfo.userType} />
						</div>
						<i className="quitlogo" onClick={this.logout}></i>
					</div>
				</div>
      </LgTopBarContainer>
		);
	}
}

export default App;
